package com.chenyi.shop.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.chenyi.common.constant.UserConstants;
import com.chenyi.common.core.domain.TreeSelect;
import com.chenyi.common.core.domain.entity.SysAdminMenu;
import com.chenyi.common.core.domain.entity.SysAdminRole;
import com.chenyi.common.core.domain.entity.SysShop;
import com.chenyi.common.core.domain.vo.*;
import com.chenyi.common.utils.DateUtils;
import com.chenyi.common.utils.StringUtils;
import com.chenyi.shop.domain.SysShopRole;
import com.chenyi.shop.mapper.SysShopRoleMapper;
import com.chenyi.shop.service.ISysShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.chenyi.shop.mapper.SysShopMenuMapper;
import com.chenyi.common.core.domain.entity.SysShopMenu;
import com.chenyi.shop.service.ISysShopMenuService;

/**
 * 菜单权限Service业务层处理
 * 
 * @author chenyi
 * @date 2020-10-24
 */
@Service
public class SysShopMenuServiceImpl implements ISysShopMenuService
{
    @Autowired
    private SysShopMenuMapper sysShopMenuMapper;

    @Autowired
    private ISysShopService shopService;

    @Autowired
    private SysShopRoleMapper roleMapper;

    /**
     * 查询菜单权限
     * 
     * @param menuId 菜单权限ID
     * @return 菜单权限
     */
    @Override
    public SysShopMenu selectSysShopMenuById(Long menuId)
    {
        return sysShopMenuMapper.selectSysShopMenuById(menuId);
    }

    /**
     * 查询菜单权限列表
     * 
     * @param sysShopMenu 菜单权限
     * @return 菜单权限
     */
    @Override
    public List<SysShopMenu> selectSysShopMenuList(SysShopMenu sysShopMenu)
    {
        return sysShopMenuMapper.selectSysShopMenuList(sysShopMenu);
    }

    /**
     * 新增菜单权限
     * 
     * @param sysShopMenu 菜单权限
     * @return 结果
     */
    @Override
    public int insertSysShopMenu(SysShopMenu sysShopMenu)
    {
        sysShopMenu.setCreateTime(DateUtils.getNowDate());
        return sysShopMenuMapper.insertSysShopMenu(sysShopMenu);
    }

    /**
     * 修改菜单权限
     * 
     * @param sysShopMenu 菜单权限
     * @return 结果
     */
    @Override
    public int updateSysShopMenu(SysShopMenu sysShopMenu)
    {
        sysShopMenu.setUpdateTime(DateUtils.getNowDate());
        return sysShopMenuMapper.updateSysShopMenu(sysShopMenu);
    }

    /**
     * 批量删除菜单权限
     * 
     * @param menuIds 需要删除的菜单权限ID
     * @return 结果
     */
    @Override
    public int deleteSysShopMenuByIds(Long[] menuIds)
    {
        return sysShopMenuMapper.deleteSysShopMenuByIds(menuIds);
    }

    /**
     * 删除菜单权限信息
     * 
     * @param menuId 菜单权限ID
     * @return 结果
     */
    @Override
    public int deleteSysShopMenuById(Long menuId)
    {
        return sysShopMenuMapper.deleteSysShopMenuById(menuId);
    }

    @Override
    public Set<String> selectShopMenuPermsByShopId(Long shopId) {
        List<String> perms = sysShopMenuMapper.selectShopMenuPermsByShopId(shopId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<SysShopMenu> selectShopMenuTreeByShopId(Long shopId) {
        List<SysShopMenu> menus = null;
        SysShop shop = shopService.selectSysShopById(shopId);
        if (shop.isAdmin())
        {
            menus = sysShopMenuMapper.selectShopMenuTreeAll();
        }
        else
        {
            menus = sysShopMenuMapper.selectShopMenuTreeByShopId(shopId);
        }
        return getChildPerms(menus, 0);
    }

    @Override
    public List<RouterVo> buildShopMenus(List<SysShopMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysShopMenu menu : menus)
        {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache())));
            List<SysShopMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType()))
            {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildShopMenus(cMenus));
            }
            else if (isMeunFrame(menu))
            {
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache())));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    @Override
    public List<SysShopMenu> selectShopMenuList(SysShopMenu menu, Long shopId) {
        List<SysShopMenu> menuList = null;
        SysShop shop = shopService.selectSysShopById(shopId);
        // 管理员显示所有菜单信息
        if (shop.isAdmin())
        {
            menuList = sysShopMenuMapper.selectShopMenuList(menu);
        }
        else
        {
            menu.getParams().put("shopId", shopId);
            menuList = sysShopMenuMapper.selectShopMenuListByShopId(menu);
        }
        return menuList;
    }

    @Override
    public List<TreeSelect> buildShopMenuTreeSelect(List<SysShopMenu> menus) {
        List<SysShopMenu> menuTrees = buildShopMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<SysShopMenu> buildShopMenuTree(List<SysShopMenu> menus)
    {
        List<SysShopMenu> returnList = new ArrayList<SysShopMenu>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysShopMenu dept : menus)
        {
            tempList.add(dept.getMenuId());
        }
        for (Iterator<SysShopMenu> iterator = menus.iterator(); iterator.hasNext();)
        {
            SysShopMenu menu = (SysShopMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId()))
            {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }

    @Override
    public List<Integer> selectShopMenuListByRoleId(Long roleId) {
        SysShopRole role = roleMapper.selectSysShopRoleById(roleId);
        return sysShopMenuMapper.selectShopMenuListByRoleId(roleId, role.isMenuCheckStrictly());
    }

    @Override
    public List<SysShopMenu> selectShopMenuList(Long shopId) {
        return selectShopMenuList(new SysShopMenu(), shopId);
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysShopMenu menu)
    {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMeunFrame(menu))
        {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysShopMenu menu)
    {
        String routerPath = menu.getPath();
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame()))
        {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMeunFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysShopMenu menu)
    {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMeunFrame(menu))
        {
            component = menu.getComponent();
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMeunFrame(SysShopMenu menu)
    {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysShopMenu> getChildPerms(List<SysShopMenu> list, int parentId)
    {
        List<SysShopMenu> returnList = new ArrayList<SysShopMenu>();
        for (Iterator<SysShopMenu> iterator = list.iterator(); iterator.hasNext();)
        {
            SysShopMenu t = (SysShopMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysShopMenu> list, SysShopMenu t)
    {
        // 得到子节点列表
        List<SysShopMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysShopMenu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysShopMenu> getChildList(List<SysShopMenu> list, SysShopMenu t)
    {
        List<SysShopMenu> tlist = new ArrayList<SysShopMenu>();
        Iterator<SysShopMenu> it = list.iterator();
        while (it.hasNext())
        {
            SysShopMenu n = (SysShopMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysShopMenu> list, SysShopMenu t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
